package br.com.sgmf.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import br.com.sgmf.model.Fornecedor;

@Repository
public class FornecedorDAO {

	@PersistenceContext
	private EntityManager manager;

	@Transactional
	public void save(Fornecedor fornecedor) {
		manager.persist(fornecedor);
	}

	@Transactional
	public void update(Fornecedor fornecedor) {
		manager.merge(fornecedor);
	}

	@Transactional
	public void delete(Fornecedor fornecedor) {
		fornecedor = manager.merge(fornecedor);
		manager.remove(fornecedor);
	}

	@Transactional(readOnly = true)
	public Fornecedor findById(Integer id) {
		return manager.find(Fornecedor.class, id);
	}

	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true)
	public List<Fornecedor> findAll() {
		return manager.createNamedQuery("Fornecedor.findAll").getResultList();
	}

	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true)
	public List<Fornecedor> findByRazaoSocial(String razaoSocial) {
		return manager.createNamedQuery("Fornecedor.findByRazaoSocial")
				.setParameter("razaoSocial", "%" + razaoSocial + "%")
				.getResultList();
	}

}
